package com.easyaop.asm;

import com.easyaop.api.around.Around;
import com.easyaop.api.around.Call;
import com.easyaop.api.event.JoinManger;
import com.easyaop.api.join.JoinImpl;
import com.easyaop.api.join.JoinPoint;

public class Around2Event implements Around {


    @Override
    public Object around(Object target, Object[] args, JoinPoint joinPoint, Call call) throws Exception {

        JoinImpl join = JoinImpl.of(joinPoint.getJavaMethod()
                .getDeclaringClass(), joinPoint.getSignature(), target, args);
        try {
            JoinManger.enter(join);

            Object ret;
            if (join.isSkipOriginMethod()) ret = join.getReturnValue();
            else ret = call.call();

            JoinManger.exit(join);
             ret = join.isChangReturn() ? join.getReturnValue() : ret;
            return ret;

        } catch (Throwable t) {
            join.setThrowable(t);
            JoinManger.onThrows(join);

            if (join.isChangReturn()) {
                return join.getReturnValue();
            }
            throw t;
        }
    }
}
